package com.example.archive.service.impl;

import com.baidu.aip.ocr.AipOcr;
import com.example.archive.service.OCRService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@Service
public class OCRServiceImpl implements OCRService {
    
    private static final Logger logger = LoggerFactory.getLogger(OCRServiceImpl.class);
    
    @Autowired
    private AipOcr aipOcr;
    
    @Override
    public String recognizeText(MultipartFile imageFile) {
        try {
            byte[] imageBytes = imageFile.getBytes();
            return recognizeText(imageBytes);
        } catch (Exception e) {
            logger.error("OCR识别失败: {}", e.getMessage());
            return "OCR识别失败: " + e.getMessage();
        }
    }
    
    @Override
    public String recognizeText(byte[] imageBytes) {
        try {
            // 调用百度OCR通用文字识别API
            HashMap<String, String> options = new HashMap<>();
            options.put("language_type", "CHN_ENG"); // 中英文混合
            options.put("detect_direction", "true"); // 检测图像朝向
            options.put("detect_language", "true"); // 检测语言
            options.put("probability", "false"); // 是否返回识别结果中每一行的置信度
            
            // 调用通用文字识别
            JSONObject result = aipOcr.basicGeneral(imageBytes, options);
            
            if (result.has("error_code")) {
                String errorMsg = result.optString("error_msg", "未知错误");
                logger.error("百度OCR API错误: {}", errorMsg);
                return "OCR识别失败: " + errorMsg;
            }
            
            // 解析识别结果
            StringBuilder recognizedText = new StringBuilder();
            if (result.has("words_result")) {
                JSONArray wordsResult = result.getJSONArray("words_result");
                for (int i = 0; i < wordsResult.length(); i++) {
                    JSONObject wordInfo = wordsResult.getJSONObject(i);
                    String words = wordInfo.optString("words", "");
                    recognizedText.append(words);
                    if (i < wordsResult.length() - 1) {
                        recognizedText.append("\n");
                    }
                }
            }
            
            String finalText = recognizedText.toString().trim();
            logger.info("OCR识别成功，识别出 {} 个字符", finalText.length());
            return finalText.isEmpty() ? "未识别到文字内容" : finalText;
            
        } catch (Exception e) {
            logger.error("OCR识别异常: {}", e.getMessage(), e);
            return "OCR识别失败: " + e.getMessage();
        }
    }
} 